package com.example.rouroudate.ui.widget

import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import com.google.android.material.tabs.TabLayout

class CenteringTabLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : TabLayout(context, attrs, defStyleAttr) {

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        val slidingTabIndicator = getChildAt(0) as? ViewGroup ?: return
        val firstTabView = slidingTabIndicator.getChildAt(0) ?: return
        val lastTabView = slidingTabIndicator.getChildAt(slidingTabIndicator.childCount - 1)
            ?: return
        val slidingTabIndicatorPaddingStart = width / 2 - firstTabView.width / 2
        val slidingTabIndicatorPaddingEnd = width / 2 - lastTabView.width / 2
        if (slidingTabIndicator.paddingStart != slidingTabIndicatorPaddingStart
            || slidingTabIndicator.paddingEnd != slidingTabIndicatorPaddingEnd) {
            slidingTabIndicator.setPadding(slidingTabIndicatorPaddingStart, 0,
                slidingTabIndicatorPaddingEnd, 0)
        }
        getTabAt(selectedTabPosition)?.let {
            selectTab(it, false)
        }
    }
}